// Splash screen code
#include "burner.h"

int splashTime = 1500;
int disableSplash = 0;

static HWND hSplashDlg = NULL;
static HANDLE hSplashThread = NULL;
static unsigned splashThreadID = 0;

static clock_t startTime;

static INT_PTR CALLBACK SplashProc(HWND hDlg, UINT msg, WPARAM /*wParam*/, LPARAM /*lParam*/)
{
	if (msg == WM_INITDIALOG) {
		hSplashDlg = hDlg;

		// ==> load custom resource, added by regret
		HBITMAP hBitmap = (HBITMAP)LoadImage(hAppInst, L"res\\splash.bmp", IMAGE_BITMAP, 304, 224, LR_LOADFROMFILE);
		if (!hBitmap) {
			hBitmap = LoadBitmap(hAppInst, MAKEINTRESOURCE(BMP_SPLASH));
		}
		SendDlgItemMessage(hDlg, IDC_SPLASH, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hBitmap);
		// <== load custom resource

		SetWindowPos(hDlg, HWND_TOPMOST, 0, 0, 304, 224, SWP_NOMOVE | SWP_SHOWWINDOW);

		SetForegroundWindow(hDlg);
		RedrawWindow(hDlg, NULL, NULL, 0);
		ShowWindow(hDlg, SW_SHOWNORMAL);

		return TRUE;
	}

	return FALSE;
}

static unsigned __stdcall doSplash(void* param)
{
	MSG msg;
	BOOL ret;

	// Raise the thread priority for this thread
	SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);

	localiseCreateDialog(IDD_SPLASH, NULL, (DLGPROC)SplashProc);

	while (1) {
		ret = GetMessage(&msg, NULL, 0, 0);

		if (ret != 0 && ret != -1) {
	    	// See if we need to end the thread
			if (msg.message == (WM_APP + 0)) {
				break;
			}

			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	DestroyWindow(hSplashDlg);

	return 0;
}

int splashCreate()
{
	if (disableSplash != 0) {
		return 1;
	}
	if (hSplashDlg || !splashTime || hSplashThread) {
		return 1;
	}

	hSplashThread = (HANDLE)_beginthreadex(NULL, 0, doSplash, NULL, 0, &splashThreadID);

	startTime = clock();

	return 0;
}

void splashDestroy(bool force)
{
	if (!hSplashThread) {
		return;
	}

	if (!force && (clock() - splashTime < startTime)) {
		return;
	}

	// Signal the splash thread to end
	PostThreadMessage(splashThreadID, WM_APP + 0, 0, 0);

	hSplashDlg = NULL;

	CloseHandle(hSplashThread);
	hSplashThread = NULL;
	splashThreadID = 0;
}
